#include "configmanager.h"
#include <QSettings>
#include <QFile>

#ifdef Q_OS_ANDROID
    #include <QGuiApplication>
    #include <QScreen>
#endif

ConfigManager::ConfigManager() {
    avatarNum = -1;

    // 如果没有文件就创建这个文件
    if(!QFile::exists("properties.ini")){
        // 创建配置文件
        QSettings*  m_IniFile = new QSettings("properties.ini", QSettings::IniFormat);

        //通过setValue函数将键值对放在相对于的节下面
#ifdef Q_OS_ANDROID
        QSize size = QGuiApplication::primaryScreen()->geometry().size(); // 获取设备宽高
        m_IniFile->setValue(QString("DEVICE") + "/" + "SCREEN_WIDTH",  size.width());
        m_IniFile->setValue(QString("DEVICE") + "/" + "SCREEN_HEIGHT",  size.height());
#else
        m_IniFile->setValue(QString("DEVICE") + "/" + "SCREEN_WIDTH",  1200);
        m_IniFile->setValue(QString("DEVICE") + "/" + "SCREEN_HEIGHT",  675);
#endif
        delete m_IniFile;
    }

    // 打开文件
    QSettings* configIni = new QSettings("properties.ini", QSettings::IniFormat);

    //读指定节点的指定数据，其中“Log”为节点，save_days为具体数据项
    screenWidth = configIni->value("DEVICE/SCREEN_WIDTH").toInt();
    screenHeight = configIni->value("DEVICE/SCREEN_HEIGHT").toInt();
    if(configIni->contains("USER/NICK_NAME")){
        nickName = configIni->value("USER/NICK_NAME").toString();
        avatarNum = configIni->value("USER/AVATAR_NUM").toInt();
    }
    delete configIni;

    // 牌与牌的间距
    cardSpacing = screenWidth / 40;

    // 牌的宽高
    cardWidth = screenWidth / 15;
    cardHeight = cardWidth * 1.39;

    // 牌弹起的高度
    cardJumpHeight = screenHeight / 67.5;

    // 我方牌的y坐标
    myCardY = screenHeight/2-cardHeight-screenHeight/15;
}

ConfigManager &ConfigManager::instance()
{
    static ConfigManager instance;
    return instance;
}

int ConfigManager::calcu_x(int num)
{
    int width = cardSpacing*(num-1) + cardWidth; // n张牌的总宽度
    return -width/2.0;
}

int ConfigManager::calcu_index(int num, QPointF pos)
{
    if(num <= 0) return -1;
    if(pos.y() < myCardY || pos.y() > myCardY+cardHeight) return -1; //-1表示没点到牌
    int start_x = calcu_x(num);
    int temp = start_x+cardSpacing*(num-1);
    if(pos.x() < start_x || pos.x() > temp + cardWidth) return -1;
    if(pos.x() >= temp && pos.x() < temp + cardWidth) return num-1; //点击的是最后一张
    return (pos.x()-start_x) / cardSpacing;
}
